// Fill out your copyright notice in the Description page of Project Settings.


#include "UI/HUD/StarrySkyHUD.h"
#include "Blueprint/UserWidget.h"
#include "UI/WidgetController/AttributeMenuWidgetController.h"
#include "UI/WidgetController/OverlayWidgetController.h"

UOverlayWidgetController* AStarrySkyHUD::GetOverlayWidgetController(const FWidgetControllerParams& WCParams)
{
	//单例模式，如果不存在就创建一个新的实例
	if(OverlayWidgetController == nullptr)
	{
		OverlayWidgetController = NewObject<UOverlayWidgetController>(this, OverlayWidgetControllerClass);
		OverlayWidgetController->SetWidgetControllerParams(WCParams);
		OverlayWidgetController->BindCallbacksToDependencies();
	}
	return OverlayWidgetController;
}

UAttributeMenuWidgetController* AStarrySkyHUD::GetAttributeMenuWidgetController(const FWidgetControllerParams& WCParams)
{
	//单例模式，如果不存在就创建一个新的实例
	if(AttributeMenuWidgetController == nullptr)
	{
		AttributeMenuWidgetController = NewObject<UAttributeMenuWidgetController>(this, AttributeMenuWidgetControllerClass);
		AttributeMenuWidgetController->SetWidgetControllerParams(WCParams);
		AttributeMenuWidgetController->BindCallbacksToDependencies();
	}
	return AttributeMenuWidgetController;
}

void AStarrySkyHUD::InitOverlay(APlayerController* PC, APlayerState* PS, UAbilitySystemComponent* ASC,
                                UAttributeSet* AS)
{
	//为了不忘记设置两个关键的变量，所以进行了检测，如果是 nullptr，则报错程序崩溃
	checkf(OverlayWidgetClass, TEXT("OverlayWidgetClass is nullptr ,没有在BP_StarrySkyHUD中进行初始化设置"));
	checkf(OverlayWidgetControllerClass, TEXT("OverlayWidgetControllerClass is nullptr ,没有在BP_StarrySkyHUD中进行初始化设置"));
	UUserWidget* Widget=CreateWidget(GetWorld(), OverlayWidgetClass);
    
	//强制转化为StarrySkyWidget，这样才能将OverlayWidgetController绑定到StarrySkyWidget上
	OverlayWidget = Cast<UStarrySkyUserWidget>(Widget);
	//设置结构体
	const FWidgetControllerParams WidgetControllerParams(PC, PS, ASC, AS);
	UOverlayWidgetController* WidgetController = GetOverlayWidgetController(WidgetControllerParams);
	//控制器和界面绑定
	OverlayWidget->SetWidgetController(WidgetController);
	//初始化广播
	WidgetController->BroadcastInitialValues();
	Widget->AddToViewport();
}

void AStarrySkyHUD::BeginPlay()
{
	Super::BeginPlay();
    UUserWidget* Widget=CreateWidget(GetWorld(),OverlayWidgetClass);
    Widget->AddToViewport();
}
